package libs

import (
	"devOpsApi/config/ymlgo"
	"errors"
	"github.com/go-gomail/gomail"
	"io"
	"io/ioutil"
	"strconv"
	"strings"
)

type EmailParam struct {
	// ServerHost 邮箱服务器地址，如腾讯企业邮箱为smtp.exmail.qq.com
	ServerHost string
	// ServerPort 邮箱服务器端口，如腾讯企业邮箱为465
	ServerPort int
	// FromEmail　发件人邮箱地址
	FromEmail string
	// FromPasswd 发件人邮箱密码（注意，这里是明文形式），TODO：如果设置成密文？
	FromPasswd string
	// Toers 接收者邮件，如有多个，则以英文逗号(“,”)隔开，不能为空
	Toers string
	// CCers 抄送者邮件，如有多个，则以英文逗号(“,”)隔开，可以为空
	CCers string
}

func SendEmail(tousers string, subject, body string, filename ...string) error {
	var ep EmailParam
	configEmail := ymlgo.NewConfigEmail()
	if configEmail.IsOpen == false {
		return errors.New("email setting is closed")
	}
	ServerPort, _ := strconv.Atoi(configEmail.ServerPort)
	ep.ServerHost = configEmail.ServerHost
	ep.ServerPort = ServerPort
	ep.FromEmail = configEmail.FromEmail
	ep.FromPasswd = configEmail.FromPasswd
	ep.Toers = tousers

	toers := []string{}

	m := gomail.NewMessage()

	if len(ep.Toers) == 0 {
		return errors.New("Toers is empty")
	}

	for _, tmp := range strings.Split(ep.Toers, ",") {
		toers = append(toers, strings.TrimSpace(tmp))
	}

	// 收件人可以有多个，故用此方式
	m.SetHeader("To", toers...)

	//抄送列表
	if len(ep.CCers) != 0 {
		for _, tmp := range strings.Split(ep.CCers, ",") {
			toers = append(toers, strings.TrimSpace(tmp))
		}
		m.SetHeader("Cc", toers...)
	}

	// 发件人
	// 第三个参数为发件人别名，如"李大锤"，可以为空（此时则为邮箱名称）
	m.SetAddressHeader("From", ep.FromEmail, "花木兰系统")
	// 主题
	m.SetHeader("Subject", subject)

	// 正文
	m.SetBody("text/html", body)

	if len(filename) > 0 {
		m.Attach(mockCopyFile(filename[0]))
	}

	d := gomail.NewDialer(ep.ServerHost, ep.ServerPort, ep.FromEmail, ep.FromPasswd)
	//d.TLSConfig = &tls.Config{InsecureSkipVerify: true}

	// 发送
	err := d.DialAndSend(m)
	if err != nil {
		return err
	}
	return nil
}

func mockCopyFile(name string) (string, gomail.FileSetting) {
	return "错误日志.log", gomail.SetCopyFunc(func(w io.Writer) error {
		data, _ := ioutil.ReadFile(name)
		_, err := w.Write(data)
		return err
	})
}
